<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Components: Interfaces and Adapters</title></head>

<body>
<h1>Components: Interfaces and Adapters</h1>

<p>Object oriented programming languages allow programmers to reuse portions of
existing code by creating new <q>classes</q> of objects which subclass another
class.  When a class subclasses another, it is said to <em>inherit</em> all of its
behaviour.  The subclass can then <q>override</q> and <q>extend</q> the behavior
provided to it by the superclass. Inheritance is very useful in many situations,
but because it is so convenient to use, often becomes abused in large software
systems, especially when multiple inheritance is involved. One solution is to
use <em>delegation</em> instead of <q>inheritance</q> where appropriate.
Delegation is simply the act of asking <em>another</em> object to perform a task
for an object. To support this design pattern, which is often referred to as the
<em>components</em> pattern because it involves many small interacting components,
<em>interfaces</em> and <em>adapters</em> were created by the Zope 3 team.</p>

<p><q>Interfaces</q> are simply markers which objects can use to say <q>I
implement this interface</q>. Other objects may then make requests like
<q>Please give me an object which implements interface X for object type Y</q>.
Objects which implement an interface for another object type are called
<q>adapters</q>.</p>

<p>The superclass-subclass relationship is said to be an <em>is-a</em> relationship.
When designing object hierarchies, object modellers use subclassing when they
can say that the subclass <em>is</em> the same class as the superclass. For
example:</p>

<pre class="python">
class Shape:
    sideLength = 0
    def getSideLength(self):
        return self.sideLength
    
    def setSideLength(self, sideLength):
        self.sideLength = sideLength

    def area(self):
        raise NotImplementedError, "Subclasses must implement area"
  
class Triangle(Shape):
    def area(self):
        return (self.sideLength * self.sideLength) / 2

class Square(Shape):
    def area(self):
        return self.sideLength * self.sideLength
</pre>

<p>In the above example, a Triangle <em>is-a</em> Shape, so it subclasses Shape,
and a Square <em>is-a</em> Shape, so it also subclasses Shape.</p>

<p>However, subclassing can get complicated, especially when Multiple
Inheritance enters the picture. Multiple Inheritance allows a class to inherit
from more than one base class. Software which relies heavily on inheritance
often ends up having both very wide and very deep inheritance trees, meaning
that one class inherits from many superclasses spread throughout the system.
Since subclassing with Multiple Inheritance means <em>implementation
inheritance</em>, locating a method's actual implementation and ensuring the
correct method is actually being invoked becomes a challenge. For example:</p>

<pre class="python">
class Area:
    sideLength = 0
    def getSideLength(self):
        return self.sideLength
    
    def setSideLength(self, sideLength):
        self.sideLength = sideLength

    def area(self):
        raise NotImplementedError, "Subclasses must implement area"

class Color:
    color = None
    def setColor(self, color):
      self.color = color
    
    def getColor(self):
      return self.color

class Square(Area, Color):
    def area(self):
        return self.sideLength * self.sideLength
</pre>

<p>The reason programmers like using implementation inheritance is because it
makes code easier to read since the implementation details of Area are in a
separate place than the implementation details of Color. This is nice, because
conceivably an object could have a color but not an area, or an area but not a
color. The problem, though, is that Square is not really an Area or a Color, but
has an area and color. Thus, we should really be using another object oriented
technique called <em>composition</em>, which relies on delegation rather than
inheritance to break code into small reusable chunks. Let us continue with the
Multiple Inheritance example, though, because it is often used in practice.</p>

<p>What if both the Color and the Area base class defined the same method,
perhaps <code>calculate</code>? Where would the implementation come from? The
implementation that is located for <code>Square().calculate()</code> depends on
the method resolution order, or MRO, and can change when programmers change
seemingly unrelated things by refactoring classes in other parts of the system,
causing obscure bugs. Our first thought might be to change the calculate method
name to avoid name clashes, to perhaps <code>calculateArea</code> and
<code>calculateColor</code>.  While explicit, this change could potentially
require a large number of changes throughout a system, and is error-prone,
especially when attempting to integrate two systems which you didn't write.</p>

<p>Let's imagine another example. We have an electric appliance, say a hair
dryer. The hair dryer is american voltage. We have two electric sockets, one of
them an american 110 Volt socket, and one of them a foreign 220 Volt socket. If
we plug the hair dryer into the 220 Volt socket, it is going to expect 110 Volt
current and errors will result. Going back and changing the hair dryer to
support both <code>plug110Volt</code> and <code>plug220Volt</code> methods would
be tedious, and what if we decided we needed to plug the hair dryer into yet
another type of socket? For example:</p>

<pre class="python">
class HairDryer:
    def plug(self, socket):
        if socket.voltage() == 110:
            print "I was plugged in properly and am operating."
        else:
            print "I was plugged in improperly and "
            print "now you have no hair dryer any more."

class AmericanSocket:
    def voltage(self):
        return 110

class ForeignSocket:
    def voltage(self):
        return 220
</pre>

<p>Given these classes, the following operations can be performed:</p>

<pre class="python-interpreter">
&gt;&gt;&gt; hd = HairDryer()
&gt;&gt;&gt; am = AmericanSocket()
&gt;&gt;&gt; hd.plug(am)
I was plugged in properly and am operating.
&gt;&gt;&gt; fs = ForeignSocket()
&gt;&gt;&gt; hd.plug(fs)
I was plugged in improperly and 
now you have no hair dryer any more.
</pre>

<p>We are going to attempt to solve this problem by writing an Adapter for the
<code>ForeignSocket</code> which converts the voltage for use with an American
hair dryer. An Adapter is a class which is constructed with one and only one
argument, the <q>adaptee</q> or <q>original</q> object. In this example, we
will show all code involved for clarity:</p>

<pre class="python">
class AdaptToAmericanSocket:
    def __init__(self, original):
        self.original = original
    
    def voltage(self):
        return self.original.voltage() / 2
</pre>

<p>Now, we can use it as so:</p>

<pre class="python-interpreter">
&gt;&gt;&gt; hd = HairDryer()
&gt;&gt;&gt; fs = ForeignSocket()
&gt;&gt;&gt; adapted = AdaptToAmericanSocket(fs)
&gt;&gt;&gt; hd.plug(adapted)
I was plugged in properly and am operating.
</pre>

<p>So, as you can see, an adapter can 'override' the original implementation. It
can also 'extend' the interface of the original object by providing methods the
original object did not have. Note that an Adapter must explicitly delegate any
method calls it does not wish to modify to the original, otherwise the Adapter
cannot be used in places where the original is expected. Usually this is not a
problem, as an Adapter is created to conform an object to a particular interface
and then discarded.</p>

<h2>Interfaces and Components in Twisted code</h2>

<p>Adapters are a useful way of using multiple classes to factor code into
discrete chunks. However, they are not very interesting without some more
infrastructure. If each piece of code which wished to use an adapted object had
to explicitly construct the adapter itself, the coupling between components
would be too tight. We would like to achieve <q>loose coupling</q>, and this is
where <code class="API">twisted.python.components</code> comes in.</p>

<p>First, we need to discuss Interfaces in more detail. As we mentioned
earlier, an Interface is nothing more than a class which is used as a marker.
Interfaces should be subclasses of <code>zope.interface.Interface</code>, and
have a very odd look to python programmers not used to them:</p>

<pre class="python">
from zope.interface import Interface

class IAmericanSocket(Interface):
    def voltage():
      """Return the voltage produced by this socket object, as an integer.
      """
</pre>

<p>Notice how it looks just like a regular class definition, other than
inheriting from <code>Interface</code>? However, the method definitions inside
the class block do not have any method body! Since Python does not have any
native language-level support for Interfaces like Java does, this is what
distinguishes an Interface definition from a Class.</p>

<p>Now that we have a defined Interface, we can talk about objects using terms
like this: <q>The <code>AmericanSocket</code> class implements the
<code>IAmericanSocket</code> interface</q> and <q>Please give me an object which
adapts <code>ForeignSocket</code> to the <code>IAmericanSocket</code>
interface</q>. We can make <em>declarations</em> about what interfaces a certain
class implements, and we can request adapters which implement a certain
interface for a specific class.</p>

<p>Let's look at how we declare that a class implements an interface:</p>

<pre class="python">
from zope.interface import implements

class AmericanSocket:

    implements(IAmericanSocket)

    def voltage(self):
        return 110
</pre>

<p>So, to declare that a class implements an interface, we simply call
<code>zope.interface.implements</code> at the class level.</p>

<p>Now, let's say we want to rewrite the <code>AdaptToAmericanSocket</code>
class as a real adapter. In this case we also specify it as implementing
<code>IAmericanSocket</code>:</p>

<pre class="python">
from zope.interface import implements

class AdaptToAmericanSocket:

    implements(IAmericanSocket)

    def __init__(self, original):
        """
        Pass the original ForeignSocket object as original
        """
        self.original = original

    def voltage(self):
        return self.original.voltage() / 2
</pre>

<p>Notice how we placed the implements declaration on this adapter class. So
far, we have not achieved anything by using components other than requiring us
to type more. In order for components to be useful, we must use the
<em>component registry</em>. Since <code>AdaptToAmericanSocket</code> implements
<code>IAmericanSocket</code> and regulates the voltage of a
<code>ForeignSocket</code> object, we can <em>register
<code>AdaptToAmericanSocket</code> as an <code>IAmericanSocket</code> adapter
for the <code>ForeignSocket</code> class</em>. It is easier to see how this is
done in code than to describe it:</p>

<pre class="python">
from zope.interface import Interface, implements
from twisted.python import components

class IAmericanSocket(Interface):
    def voltage():
      """Return the voltage produced by this socket object, as an integer.
      """
    
class AmericanSocket:
    implements(IAmericanSocket)

    def voltage(self):
        return 110

class ForeignSocket:
    def voltage(self):
        return 220

class AdaptToAmericanSocket:

    implements(IAmericanSocket)

    def __init__(self, original):
        self.original = original

    def voltage(self):
        return self.original.voltage() / 2
    
components.registerAdapter(
    AdaptToAmericanSocket, 
    ForeignSocket, 
    IAmericanSocket)
</pre>

<p>Now, if we run this script in the interactive interpreter, we can discover a
little more about how to use components. The first thing we can do is discover
whether an object implements an interface or not:</p>

<pre class="python-interpreter">
&gt;&gt;&gt; IAmericanSocket.implementedBy(AmericanSocket)
True
&gt;&gt;&gt; IAmericanSocket.implementedBy(ForeignSocket)
False
&gt;&gt;&gt; as = AmericanSocket() 
&gt;&gt;&gt; fs = ForeignSocket()
&gt;&gt;&gt; IAmericanSocket.providedBy(as)
True
&gt;&gt;&gt; IAmericanSocket.providedBy(fs)
False
</pre>

<p>As you can see, the <code>AmericanSocket</code> instance claims to
implement <code>IAmericanSocket</code>, but the <code>ForeignSocket</code>
does not. If we wanted to use the <code>HairDryer</code> with the
<code>AmericanSocket</code>, we could know that it would be safe to do so by
checking whether it implements <code>IAmericanSocket</code>. However, if we
decide we want to use <code>HairDryer</code> with a <code>ForeignSocket</code>
instance, we must <em>adapt</em> it to <code>IAmericanSocket</code> before
doing so.  We use the interface object to do this:</p>

<pre class="python-interpreter">
&gt;&gt;&gt; IAmericanSocket(fs)
&lt;__main__.AdaptToAmericanSocket instance at 0x1a5120&gt;
</pre>

<p>When calling an interface with an object as an argument, the interface
looks in the adapter registry for an adapter which implements the interface for
the given instance's class. If it finds one, it constructs an instance of the
Adapter class, passing the constructor the original instance, and returns it.
Now the <code>HairDryer</code> can safely be used with the adapted
<code>ForeignSocket</code>. But what happens if we attempt to adapt an object
which already implements <code>IAmericanSocket</code>? We simply get back the
original instance:</p>

<pre class="python-interpreter">
&gt;&gt;&gt; IAmericanSocket(as)
&lt;__main__.AmericanSocket instance at 0x36bff0&gt;
</pre>

<p>So, we could write a new <q>smart</q> <code>HairDryer</code> which
automatically looked up an adapter for the socket you tried to plug it into:</p>

<pre class="python">
class HairDryer:
    def plug(self, socket):
        adapted = IAmericanSocket(socket)
        assert adapted.voltage() == 110, "BOOM"
        print "I was plugged in properly and am operating"
</pre>

<p>Now, if we create an instance of our new <q>smart</q> <code>HairDryer</code>
and attempt to plug it in to various sockets, the <code>HairDryer</code> will
adapt itself automatically depending on the type of socket it is plugged in
to:</p>

<pre class="python-interpreter">
&gt;&gt;&gt; as = AmericanSocket()
&gt;&gt;&gt; fs = ForeignSocket()
&gt;&gt;&gt; hd = HairDryer()
&gt;&gt;&gt; hd.plug(as)
I was plugged in properly and am operating
&gt;&gt;&gt; hd.plug(fs)
I was plugged in properly and am operating
</pre>
    
<p>Voila; the magic of components.</p>

<h3>Components and Inheritance</h3>

<p>If you inherit from a class which implements some interface, and your new
subclass declares that it implements another interface, the implements will be
inherited by default.</p>

<p>For example, <code base="twisted.spread">pb.Root</code> (actually defined
in <code class="API" base="twisted.spread">flavors.Root</code>) is a class
which implements <code class="API"
base="twisted.spread.flavors">IPBRoot</code>. This interface indicates that an
object has remotely-invokable methods and can be used as the initial object
served by a new Broker instance. It has an <code>implements</code> setting
like:</p>

<pre class="python">
from zope.interface import implements

class Root(Referenceable):
    implements(IPBRoot)
</pre>

<p>Suppose you have your own class which implements your
<code>IMyInterface</code> interface:</p>

<pre class="python">
from zope.interface import implements, Interface

class IMyInterface(Interface):
    pass

class MyThing:
    implements(IMyInterface)
</pre>

<p>Now if you want to make this class inherit from <code>pb.Root</code>, 
the interfaces code will automatically determine that it also implements
<code>IPBRoot</code>:</p>

<pre class="python">
from twisted.spread import pb
from zope.interface import implements, Interface

class IMyInterface(Interface):
    pass

class MyThing(pb.Root):
    implements(IMyInterface)
</pre>

<pre class="python-interpreter">
&gt;&gt;&gt; from twisted.spread.flavors import IPBRoot
&gt;&gt;&gt; IPBRoot.implementedBy(MyThing)
True
</pre>

<p>If you want <code>MyThing</code> to inherit from <code>pb.Root</code> but
<em>not</em> implement <code>IPBRoot</code> like <code>pb.Root</code> does,
use <code>implementOnly</code>:</p>

<pre class="python">
from twisted.spread import pb
from zope.interface import implementsOnly, Interface

class IMyInterface(Interface):
    pass

class MyThing(pb.Root):
    implementsOnly(IMyInterface)
</pre>

<pre class="python-interpreter">
&gt;&gt;&gt; from twisted.spread.flavors import IPBRoot
&gt;&gt;&gt; IPBRoot.implementedBy(MyThing)
False
</pre>

</body>

</html>

